<template>
	<div class="my-chart-edit-tools aside">
		<n-tooltip v-for="item in btnList" :key="item.key" trigger="hover" placement="left">
			<template #trigger>
				<div class="btn-item">
					<n-button v-if="item.type === 'button'" circle secondary @click="item.handle">
						<template #icon>
							<n-icon size="22"><component :is="item.icon"></component></n-icon>
						</template>
					</n-button>
					<!-- 导入 -->
					<n-upload
						v-else-if="item.type === 'importUpload'"
						:show-file-list="false"
						:customRequest="importCustomRequest"
						@before-upload="importBeforeUpload"
					>
						<n-button circle secondary>
							<template #icon>
								<n-icon size="22"><component :is="item.icon"></component></n-icon>
							</template>
						</n-button>
					</n-upload>
				</div>
			</template>
			<!-- 提示 -->
			<span>{{ item.name }}</span>
		</n-tooltip>
	</div>
</template>

<script setup>
import { downloadTextFile, JSONStringify, JSONParse, readFile, getUUID } from '@/utils';

// 配置列表
const btnList = [
	{
		key: 'import',
		type: 'importUpload',
		name: '导入',
		icon: 'Upload'
	},
	{
		key: 'export',
		type: 'button',
		name: '导出',
		icon: 'Download',
		handle: () => {
			// 导出数据
			downloadTextFile(JSONStringify($store.chart.getStorageInfo || {}), undefined, 'json');
		}
	}
];

// 上传-前置
function importBeforeUpload({ file }) {
	const type = file.file.type;
	if (type !== 'application/json' && type !== 'text/plain') {
		msgWarning('仅支持上传 【JSON】 格式文件，请重新上传！');
		return false;
	}
	return true;
}

// 上传-导入
async function importCustomRequest({ file }) {
	nextTick(() => {
		if (file.file) {
			readFile(file.file).then((fileData) => {
				try {
					fileData = JSONParse(fileData);
					$store.chart.editCanvasConfig = fileData.editCanvasConfig;

					!(function changeId(data = fileData.componentList) {
						data.forEach((item) => {
							item.id = getUUID();
							if (data.groupList) changeId(data.groupList);
						});
					})();

					$store.chart.componentList = fileData.componentList;

					msgSuccess('导入成功！');
				} catch (error) {
					console.log(error);
					msgError('组件导入失败，请检查文件完整性！');
				}
			});
		} else {
			msgError('导入失败，请检查数据或联系管理员！');
		}
	});
}
</script>

<style lang="scss" scoped>
@include b('chart-edit-tools') {
	background-color: var(--color-bg-4);
	position: absolute;
	display: flex;
	justify-content: space-around;
	align-items: center;
	border-radius: 25px;
	border: 1px solid var(--color-bg-5-shallow);
	backdrop-filter: blur(20px);
	box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
	&.aside {
		flex-direction: column-reverse;
		height: auto;
		right: 10px;
		padding: 15px 5px;
		bottom: 50px;
		overflow: hidden;
		.btn-item {
			margin-bottom: 10px;
			&:first-of-type {
				margin-bottom: 0;
			}
			:deep() {
				.n-button__icon {
					margin-right: 0;
					margin-left: 0;
					margin-bottom: 12px;
				}
			}
		}
	}
}
</style>
